package com.ebways.rpc.service.consumer;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

/**
 * Created by gmq on 2017/08/29.
 *
 * @version 1.0
 * @since 2017/08/29 11:14
 */
public class RpcConsumer {

    public static Object remote(final Class clazz) {
        // 动态代理
        return Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz},
                new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Socket socket = new Socket("127.0.0.1", 6666);
                        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

                        // 反射：4个条件： 类的名称（包名+类名），方法的名称，入参参数的类型，入参参数的值
                        oos.writeUTF(clazz.getName());
                        oos.writeUTF(method.getName());
                        oos.writeObject(method.getParameterTypes());
                        oos.writeObject(args);
                        oos.flush();

                        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                        Object result = ois.readObject();

                        oos.close();
                        ois.close();
                        socket.close();
                        return result;
                    }
                });
    }
}
